package com.huanletao.spring.multdatasource.service;


import com.huanletao.spring.multdatasource.DataSource;
import com.huanletao.spring.multdatasource.dao.ResumeRepository;
import com.huanletao.spring.multdatasource.dao.StudentRepository;
import com.huanletao.spring.multdatasource.pojo.Resume;
import com.huanletao.spring.multdatasource.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 */
@Service
public class ResumeService {
    @Autowired
    ResumeRepository resumeRepository;

    @Autowired
    StudentRepository studentRepository;

    @Autowired
    StudentService studentService;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Transactional(rollbackFor = Exception.class,transactionManager = "transactionManagerMaster")
    public void insert(){
        Resume resume = new Resume();
        resume.setAddress("222323");
        resume.setPhone("18207700421");
        resume.setName("admin");
        String sql = "insert into tb_resume(name,phone,address) values(?,?,?)";
        jdbcTemplate.update(sql,resume.getName(),resume.getPhone(),resume.getAddress());
        int i = 1/0;
    }

    @DataSource("slave")
    @Transactional(rollbackFor = Exception.class,transactionManager = "transactionManagerMaster")
    public void selectStudents(){
        List<Student> all = studentRepository.findAll();
        System.out.println("all = " + all);
    }

    /**
     * 两个数据源事务同时配置。
     */
    @Transactional(transactionManager = "transactionManagerMaster")
    public void twoInsert(){
        Resume resume = new Resume();
        resume.setAddress("222323");
        resume.setPhone("18207700421");
        resume.setName("admin");
        Resume save = resumeRepository.save(resume);
        studentService.insertStudent();
    }

}
